<template>
  <div class="login_container">
    <div class="login_box">
      <h2>商品后台登录系统</h2>
      <!-- 登陆表单区域 -->
      <el-form
        ref="loginForm"
        class="login_form"
        :rules="loginFormRules"
        :model="loginForm"
      >
        <!-- 用户名 -->
        <el-form-item prop="account">
          <el-input
            v-model="loginForm.account"
            placeholder="请输入用户名"
            prefix-icon="el-icon-user"
            autocomplete="on"
          ></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="pwd">
          <el-input
            ref="password"
            :type="pwdtype"
            v-model="loginForm.pwd"
            placeholder="请输入密码"
            prefix-icon="el-icon-lock"
            autocomplete="on"
          >
            <i slot="suffix" @click="showPwd" :class="passwordType"></i>
          </el-input>
        </el-form-item>
        <!-- 验证码 -->
        <el-form-item prop="code" class="captcha">
          <div class="captcha1">
            <el-input
              ref="username"
              v-model="loginForm.code"
              style="width: 168px"
              prefix-icon="el-icon-message"
              placeholder="验证码"
              name="username"
              type="text"
              autocomplete="on"
            />
            <div class="imgs" @click="getCaptcha()">
              <img :src="captchatImg" />
            </div>
          </div>
        </el-form-item>
        <!-- 按钮区域 -->
        <el-form-item class="btns">
          <el-button
            type="primary"
            @click.native.prevent="handleLogin"
            >登陆</el-button
          >
          <el-button type="info" @click="resetLoginForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { captchaApi, } from "@/api/user";
export default {
  data() {
    return {
      // 密码框后面小眼睛状态
      passwordType: "el-input__icon el-icon-date",
      pwdtype: "password",
      // 登陆表单的数据绑定对象
      // 验证码表单
      captchatImg: "",
      loginForm: {
        account: "wangzhii",
        pwd: "123123",
        code: "",
        key: "",
        wxCode: "",
      },
      redirect: undefined,
      otherQuery: {},
      // loading:'',
      // 表单的验证规则对象
      loginFormRules: {
        // 验证用户名是否合法
        account: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 5,
            max: 12,
            message: "长度在 5 到 12 个字符",
            trigger: "blur",
          },
        ],
        // 验证密码是否合法
        pwd: [
          { required: true, message: "请输入用户密码", trigger: "blur" },
          {
            min: 5,
            max: 12,
            message: "长度需要在6和30之间",
            trigger: "blur",
          },
        ],
        // 验证码验证
        code: [
          { required: true, message: "请输入正确的验证码", trigger: "blur" },
        ],
      },
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true,
    },
  },
  mounted() {
    this.getCaptcha();
  },
  methods: {
    // 密码显示状态的点击事件
    showPwd() {
      if (this.pwdtype === "password") {
        this.pwdtype = "Text";
        this.passwordType = "el-input__icon el-icon-lock";
      } else {
        this.pwdtype = "password";
        this.passwordType = "el-input__icon el-icon-date";
      }
    },







    // 验证码图片点击事件
    getCaptcha() {
      // console.log("123123");
      // const res = await captchaApi();

      // console.log(res);
      // if (res.data.code === 200) {
      //   console.log("123");
      //   this.captchatImg = res.data.data.code;
      //   this.loginForm.key = res.data.data.key;
      // } else {
      //   this.$message.error(res.data.message);
      //   console.log("55555");
      // }

      captchaApi()
        .then(({ data }) => {
          // console.log('123');
          this.captchatImg = data.code;
          this.loginForm.key = data.key;
        })
        .catch(({ message }) => {
          // console.log(message);
          // this.captchatImg = data.data.code;
          // this.loginForm.key = data.data.key;
          this.$message.error(message);
        });
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },
    // 重置登录表单
    resetLoginForm() {
      this.$refs.loginFormRef.resetFields();
    },
    // 点击登录事件
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          // console.log(valid)
          // this.loading = true;
          this.$store.dispatch("user/login", this.loginForm)
            .then((res) => {
              console.log("555");
              this.$router.push({
                path: this.redirect || "/",
                query: this.otherQuery,
              });
              // this.$store.dispatch.getInfo()

              // this.loading = false;
              // this.$root.closeNotice();

              // this.$root.notice = notice(res.token);
              console.log(res)
            })
            .catch((error) => {
              // console.log('888')
              this.loginForm.code = "";
              this.$message.error(error.message);
              // this.loading = false;
              this.getCaptcha();
            });
        } else {
          return false;
        }
      });
    },
    // login() {
    //     this.$refs.loginFormRef.validate(async valid=>{
    //       if(!valid) return
    //       const res = await this.$http.post('/admin/login',this.loginForm)
    //       console.log(res)

    //       if(res.data.code !==200) return this.$message.error("失败")
    //       this.$message.success("成功")
    //       console.log(res)
    //       // 1 将登录成功后的token，保存到客户端的sessionStrage中
    //       //   1.1 项目中除了登陆之外的其他api接口，必须在登陆之后才能访问
    //       //   1.2 token 只能在当前网站打开期间生效，所以将token保存到sessionStorage中
    //       window.sessionStorage.setItem("token",res.data.data.token)
    //       // 2.通过编程式导航跳转到后台主页，路由器是/home
    //       this.$router.push({
    //             path: this.redirect || "/",
    //           });
    //     });
    // },
  },
};
</script>

<style lang="less" scoped>
.login_container {
  background-color: #2b4b6b;
  height: 100%;
  position: relative;
  .login_box {
    h2 {
      position: absolute;
      left: 50%;
      top: 20px;
      transform: translateX(-50%);
    }
    width: 450px;
    height: 400px;
    background-color: #ffffff;
    border-radius: 7px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);

    .login_form {
      position: absolute;
      bottom: 0;
      width: 100%;
      padding: 0 30px;
      box-sizing: border-box;
    }
    .captcha1 {
      display: flex;
      justify-content: space-between;
      width: 300px;

      .imgs {
        img {
          height: 40px;
          border: #bac3cc solid 2px;
          box-sizing: border-box;
          border-radius: 4px;
        }
      }
    }
    .btns {
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>